package com.example.gobang.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import okhttp3.*;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.IOException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
public class AiController extends WebSocketListener {
    private static final String APPID = "589df5f6";
    private static final String API_SECRET = "MDIyZmNlZTdjNjhkZjNmNTRiNjFmNWJj";
    private static final String API_KEY = "91084dd8b35880610d752d1ba5912775";
    private static final String HOST_URL = "https://spark-api.xf-yun.com/v4.0/chat";
    private static final String DOMAIN = "4.0Ultra";
    private static final Gson gson = new Gson();
    private static final List<RoleContent> historyList = new ArrayList<>();

    // 调用星火大模型
    public static String callSparkModel(String prompt) throws Exception {
        String userId = "10284711用户";
        String authUrl = getAuthUrl(HOST_URL, API_KEY, API_SECRET);
        OkHttpClient client = new OkHttpClient.Builder().build();
        String url = authUrl.replace("http://", "ws://").replace("https://", "wss://");
        Request request = new Request.Builder().url(url).build();
        BigModelResponse responseHandler = new BigModelResponse();
        WebSocket webSocket = client.newWebSocket(request, responseHandler);

        JSONObject requestJson = new JSONObject();

        JSONObject header = new JSONObject();
        header.put("app_id", APPID);
        header.put("uid", UUID.randomUUID().toString().substring(0, 10));

        JSONObject parameter = new JSONObject();
        JSONObject chat = new JSONObject();
        chat.put("domain", DOMAIN);
        chat.put("temperature", 0.1);
        chat.put("max_tokens", 8192);
        parameter.put("chat", chat);

        JSONObject payload = new JSONObject();
        JSONObject message = new JSONObject();
        JSONArray text = new JSONArray();

        if (historyList.size() > 0) {
            for (RoleContent tempRoleContent : historyList) {
                text.add(JSON.toJSON(tempRoleContent));
            }
        }

        RoleContent roleContent = new RoleContent();
        roleContent.setRole("user");
        roleContent.setContent(prompt);
        text.add(JSON.toJSON(roleContent));
        historyList.add(roleContent);

        message.put("text", text);
        payload.put("message", message);

        requestJson.put("header", header);
        requestJson.put("parameter", parameter);
        requestJson.put("payload", payload);

        webSocket.send(requestJson.toString());

        synchronized (responseHandler) {
            responseHandler.wait(10000);
        }

        webSocket.close(1000, "");
        return responseHandler.getTotalAnswer();
    }

    static class BigModelResponse extends WebSocketListener {
        private String totalAnswer = "";

        @Override
        public void onOpen(WebSocket webSocket, Response response) {
            super.onOpen(webSocket, response);
        }

        @Override
        public void onMessage(WebSocket webSocket, String text) {
            JsonParse myJsonParse = gson.fromJson(text, JsonParse.class);
            if (myJsonParse.header.code != 0) {
                System.out.println("发生错误，错误码为：" + myJsonParse.header.code);
                System.out.println("本次请求的sid为：" + myJsonParse.header.sid);
                webSocket.close(1000, "");
                synchronized (this) {
                    this.notifyAll();
                }
                return;
            }
            List<Text> textList = myJsonParse.payload.choices.text;
            for (Text temp : textList) {
                totalAnswer += temp.content;
            }
            if (myJsonParse.header.status == 2) {
                if (canAddHistory()) {
                    RoleContent roleContent = new RoleContent();
                    roleContent.setRole("assistant");
                    roleContent.setContent(totalAnswer);
                    historyList.add(roleContent);
                } else {
                    historyList.remove(0);
                    RoleContent roleContent = new RoleContent();
                    roleContent.setRole("assistant");
                    roleContent.setContent(totalAnswer);
                    historyList.add(roleContent);
                }
                synchronized (this) {
                    this.notifyAll();
                }
            }
        }

        @Override
        public void onFailure(WebSocket webSocket, Throwable t, Response response) {
            super.onFailure(webSocket, t, response);
            try {
                if (response != null) {
                    int code = response.code();
                    System.out.println("onFailure code:" + code);
                    if (response.body() != null) {
                        System.out.println("onFailure body:" + response.body().string());
                    }
                    if (101 != code) {
                        System.out.println("connection failed");
                    }
                }
            } catch (IOException e) {
                System.err.println("处理失败响应时发生错误: " + e.getMessage());
            }
            synchronized (this) {
                this.notifyAll();
            }
        }

        public String getTotalAnswer() {
            return totalAnswer;
        }
    }

    public static boolean canAddHistory() {
        int historyLength = 0;
        for (RoleContent temp : historyList) {
            historyLength += temp.content.length();
        }
        if (historyLength > 12000) {
            for (int i = 0; i < 5 && !historyList.isEmpty(); i++) {
                historyList.remove(0);
            }
            return false;
        }
        return true;
    }

    public static String getAuthUrl(String hostUrl, String apiKey, String apiSecret) throws Exception {
        URL url = new URL(hostUrl);
        SimpleDateFormat format = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
        format.setTimeZone(TimeZone.getTimeZone("GMT"));
        String date = format.format(new Date());

        String preStr = "host: " + url.getHost() + "\n" +
                "date: " + date + "\n" +
                "GET " + url.getPath() + " HTTP/1.1";

        Mac mac = Mac.getInstance("hmacsha256");
        SecretKeySpec spec = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), "hmacsha256");
        mac.init(spec);

        byte[] hexDigits = mac.doFinal(preStr.getBytes(StandardCharsets.UTF_8));
        String sha = Base64.getEncoder().encodeToString(hexDigits);

        String authorization = String.format("api_key=\"%s\", algorithm=\"%s\", headers=\"%s\", signature=\"%s\"",
                apiKey, "hmac-sha256", "host date request-line", sha);

        HttpUrl httpUrl = Objects.requireNonNull(HttpUrl.parse("https://" + url.getHost() + url.getPath())).newBuilder()
                .addQueryParameter("authorization", Base64.getEncoder().encodeToString(authorization.getBytes(StandardCharsets.UTF_8)))
                .addQueryParameter("date", date)
                .addQueryParameter("host", url.getHost())
                .build();

        return httpUrl.toString();
    }

    static class JsonParse {
        Header header;
        Payload payload;
    }

    static class Header {
        int code;
        int status;
        String sid;
    }

    static class Payload {
        Choices choices;
    }

    static class Choices {
        List<Text> text;
    }

    static class Text {
        String role;
        String content;
    }

    static class RoleContent {
        String role;
        String content;

        public String getRole() {
            return role;
        }

        public void setRole(String role) {
            this.role = role;
        }

        public String getContent() {
            return content;
        }

        public void setContent(String content) {
            this.content = content;
        }
    }

    @PostMapping(value = "/ai_move")
    public Map<String, Integer> getAIMove(@RequestBody Map<String, String> request) throws Exception {
        try {
            String boardText = request.get("board_text");
            System.out.println("接收到信息：" + "\n" + boardText);
            String aiResponse = callSparkModel(boardText + "这是五子棋棋盘，请仔细思考后直接返回你要下的位置(玩家的棋子用1表示，你的棋子用2表示，0表示空)，格式为x,y，其中x为列数，y为行数，例如3,4表示第2列第3行。每次请求请给出不同的结果。");
            System.out.println("Ai返回信息：\n" + aiResponse);

            String[] parts = aiResponse.split(",");
            if (parts.length == 2) {
                int col = Integer.parseInt(parts[0].trim());
                int row = Integer.parseInt(parts[1].trim());
                Map<String, Integer> result = new HashMap<>();
                result.put("col", col);
                result.put("row", row);
                System.out.println("处理后的Ai返回信息+" + result);
                return result;
            } else {
                throw new IllegalArgumentException("AI 返回格式错误，期望 x,y 格式，实际返回: " + aiResponse);
            }
        } catch (Exception e) {
            System.err.println("处理请求时发生错误: " + e.getMessage());
            System.err.println("错误堆栈信息: " + Arrays.toString(e.getStackTrace()));
        }
        return null;
    }
}